package com.spdd.mt.biz.manager.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.spdd.mt.biz.config.SpddMapping;
import com.spdd.mt.biz.manager.channel.SpddService;
import com.spdd.mt.biz.manager.feign.request.ProductMaintenanceRequest;
import com.spdd.mt.biz.manager.feign.request.ProductRequest;
import com.spdd.mt.biz.manager.model.WebResponse;
import com.spdd.mt.biz.manager.model.request.PhoneZoneRequest;
import com.spdd.mt.biz.manager.model.request.ProductQueryRequest;
import com.spdd.mt.biz.manager.model.request.ProductStatusRequest;
import com.spdd.mt.biz.manager.model.response.*;
import com.spdd.mt.biz.constant.MtResponseStatus;
import com.spdd.mt.biz.entity.MtProductEntity;
import com.spdd.mt.biz.service.MtProductService;
import com.spdd.mt.common.util.JacksonUtils;
import com.spdd.mt.common.util.MoneyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 商品相关服务
 *
 * @since 2025年04月04日
 */
@Slf4j
@Service
public class ProductService {

    @Autowired
    private SpddMapping spddMapping;

    @Autowired
    private SpddService spddService;

    @Autowired
    private MtProductService productService;

    @Autowired
    private NotifyService notifyService;

    /**
     * 查询商品和维护信息接口
     *
     * @param queryRequest 查询参数
     */
    public ProductQueryResponse productQuery(ProductQueryRequest queryRequest) {
        if (Objects.isNull(queryRequest.getType())) {
            queryRequest.setType(1);
        }
        List<MtProductEntity> productList = productService.listByMerchNoAndType(queryRequest.getMerchNo(), queryRequest.getType());

        ProductQueryResponse response = new ProductQueryResponse(WebResponse.success(MtResponseStatus.SUCCESS));

        response.setProducts(productList.stream().map(p -> Product.builder()
                .type(p.getProductType())
                .productCode(p.getProductCode())
                .productName(p.getProductName())
                .ispName(p.getOperatorName())
                .province(p.getProvinceName())
                .facePrice(String.valueOf(p.getFacePrice()))
                .contractPrice(MoneyUtil.fenToYuan(new BigDecimal(p.getPrice()).multiply(p.getDiscount()).setScale(0, RoundingMode.HALF_UP).toString()))
                .status(p.getMaintenanceStatus())
                .build()).toList());

        return response;
    }

    /**
     * 查询单个商品的状态信息
     *
     * @param statusRequest 查询参数
     */
    public ProductStatusResponse productStatusQuery(ProductStatusRequest statusRequest) {

        MtProductEntity product = productService.getByMerchNoAndProductCode(statusRequest.getMerchNo(), statusRequest.getProductCode());

        if (Objects.isNull(product)) {
            return new ProductStatusResponse(WebResponse.fail(MtResponseStatus.PRODUCT_NOT_EXISTS));
        }

        ProductStatusResponse response = new ProductStatusResponse(WebResponse.success(MtResponseStatus.SUCCESS));
        response.setProduct(Product.builder()
                .type(product.getProductType())
                .productCode(product.getProductCode())
                .productName(product.getProductName())
                .ispName(product.getOperatorName())
                .province(product.getProvinceName())
                .facePrice(String.valueOf(product.getFacePrice()))
                .contractPrice(MoneyUtil.fenToYuan(new BigDecimal(product.getPrice()).multiply(product.getDiscount())
                        .setScale(0, RoundingMode.HALF_UP).toString()))
                .status(product.getMaintenanceStatus())
                .build());

        return response;
    }

    /**
     * 手机号码归属地查询
     *
     * @param phoneZoneRequest 查询参数
     */
    public PhoneZoneResponse phoneZoneQuery(PhoneZoneRequest phoneZoneRequest) {

        SpddPhoneZoneRes spddPhoneZoneRes = spddService.phoneZoneQuery(phoneZoneRequest.getMerchNo(), phoneZoneRequest.getPhoneNo());

        if (Objects.isNull(spddPhoneZoneRes)) {
            return new PhoneZoneResponse(WebResponse.fail(MtResponseStatus.FAIL));
        }

        PhoneZoneResponse response = new PhoneZoneResponse(WebResponse.success(MtResponseStatus.SUCCESS));
        response.setIsp(spddPhoneZoneRes.getIsp());
        response.setProvince(spddPhoneZoneRes.getProvince());
        response.setPhoneNoType(spddPhoneZoneRes.isTrans() ? "2" : "1");

        return response;
    }

    /**
     * 商品维护信息处理服务
     *
     * @param maintenanceRequest 维护请求参数
     */
    public WebResponse productMaintenanceUpdate(ProductMaintenanceRequest maintenanceRequest) {
        if (CollectionUtil.isEmpty(maintenanceRequest.getProductList())) {
            return WebResponse.fail(MtResponseStatus.FAIL, "商品集合为空");
        }

        Map<String, List<ProductRequest>> groupList = maintenanceRequest.getProductList().stream().collect(Collectors.groupingBy(ProductRequest::getSpddAppId));
        for (Map.Entry<String, List<ProductRequest>> entry : groupList.entrySet()) {
            String merchNo = SpddMapping.getKeyByAppId(spddMapping.getMapping(), entry.getKey());

            if (StrUtil.isBlank(merchNo)) {
                log.info("获取商户号失败，appId = {}", entry.getKey());
                return WebResponse.fail(MtResponseStatus.FAIL, "无法获取商户号");
            }

            // 获取商品集合
            List<String> productCodes = entry.getValue().stream().map(ProductRequest::getProductCode).collect(Collectors.toList());
            List<MtProductEntity> list = productService.list(new QueryWrapper<MtProductEntity>().lambda()
                    .eq(MtProductEntity::getMerchNo, merchNo)
                    .in(MtProductEntity::getProductCode, productCodes)
            );
            if (CollectionUtil.isEmpty(list)) {
                // return WebResponse.fail(MtResponseStatus.FAIL, "找到商品信息");
                continue;
            }

            List<MtProductEntity> updateList = list.stream().map(p -> {
                ProductRequest findProduct = entry.getValue().stream().filter(
                        pp -> pp.getProductCode().equals(p.getProductCode())
                ).findFirst().orElse(null);
                if (Objects.nonNull(findProduct)) {
                    return MtProductEntity.builder()
                            .id(p.getId())
                            .productCode(p.getProductCode())
                            .maintenanceStatus(findProduct.getMaintenanceStatus())
                            .build();
                }
                return MtProductEntity.builder()
                        .id(p.getId())
                        .productCode(p.getProductCode())
                        .maintenanceStatus(p.getMaintenanceStatus())
                        .build();
            }).collect(Collectors.toList());

            log.info("更新商品维护信息，维护内容:{}", JacksonUtils.toJson(updateList));
            productService.updateBatchById(updateList);

            // 通知美团维护内容
            notifyService.notifyMtProduct(merchNo, updateList);
        }

        return WebResponse.success(MtResponseStatus.SUCCESS);
    }
}








